package com.huafv.flyauth.web.admin.controller;

import com.huafv.flyauth.common.dto.SysMenuDto;
import com.huafv.flyauth.core.domain.Result;
import com.huafv.flyauth.core.redis.RedisCache;
import com.huafv.flyauth.security.LoginUser;
import com.huafv.flyauth.web.admin.entity.SysMenu;
import com.huafv.flyauth.web.admin.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/menus")
public class SysMenuController extends BaseController {


    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    RedisCache redisCache;

    // 获取用户权限
    @PostMapping("/authorities")
    public Result authorities(Principal principal) {
        LoginUser user = redisCache.getCacheObject("login:" + principal.getName());
        return Result.success(user.getPermissions());
    }
    // 获取菜单栏
    @PostMapping("/list")
    public Result list(Principal principal) {
        String name = principal.getName();
        List<SysMenuDto> menuList = sysMenuService.getCurrentUserMenu(name);
        return Result.success(menuList);
    }

    // 获取所有菜单信息
    @PreAuthorize("hasAuthority('menu:list')")
    @GetMapping ("/list")
    public Result listAll() {

        List<SysMenu> sysMenus = sysMenuService.allMenusTree();
        return Result.success(sysMenus);
    }

    // 获取单个菜单信息
    @PreAuthorize("hasAuthority('menu:info')")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id")Long userid) {
        SysMenu sysMenu = sysMenuService.getMenuInfo(userid);
        return Result.success(sysMenu);
    }

    @PreAuthorize("hasAuthority('menu:updateAndsave')")
    @PostMapping("/{type}")
    public Result save(@PathVariable(name = "type")String type,@RequestBody Map<String, Object> objectMap) {

        int i = 0;
        if(type.equals("update")){
            i = sysMenuService.updateMenuInfo(objectMap);
        }else if(type.equals("save")){
            i = sysMenuService.saveMenuInfo(objectMap);
        }
        return Result.success(i > 0);
    }

}
